package net.youpo.Market.data;

import java.util.ArrayList;

import net.youpo.Market.Bean.AppInfoBean;
import net.youpo.Market.Net.HttpConnection;
import net.youpo.Market.Util.ConstantsTable;
import net.youpo.Market.Util.GlobalVariables;
import net.youpo.Market.db.MarketDatabase;
import net.youpo.Market.db.HomePage.HomeRecommendTable;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.preference.PreferenceManager;
import android.util.Log;

public class DataLoader {
	private final int totalPage = 6;// 总加载90条数据
	private String mReqsConfig;
	private int nowPage = 0;
	private boolean isLoading = false;
	private boolean isEnd = false;
	private Context mContext;
	private ILoadDataResponse mDataResponse;
	private ArrayList<AppInfoBean> mAppBeanList = new ArrayList<AppInfoBean>();
	private String mTableName;
	private String mTableSQL;

	public DataLoader(Context context, String requestType,
			ILoadDataResponse dataResponse, String tableName, String tableSQL) {
		this.mContext = context;
		this.mReqsConfig = requestType;
		this.mDataResponse = dataResponse;
		this.mTableName = tableName;
		this.mTableSQL = tableSQL;
	}

	public boolean isLoading() {
		return this.isLoading;
	}

	public boolean isEnd() {
		return this.isEnd;
	}

	public void loadNext() {
		new Thread() {
			@Override
			public void run() {
				super.run();
				isLoading = true;
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				if (nowPage++ < totalPage) {
					isEnd = false;
					SharedPreferences sPreferences = PreferenceManager
							.getDefaultSharedPreferences(mContext);
					long lastUpdateTime = sPreferences.getLong(
							ConstantsTable.HOMEPAGE_RECOMMEND, 0);
					long nowTime = System.currentTimeMillis();

					// 1.判断是否需要更新，如果要更新就清空数据库
					if ((nowTime - lastUpdateTime) > GlobalVariables.DATA_REFRESH_TIME) {
						SQLiteDatabase marketDB = MarketDatabase.getMarketDB();
						marketDB.execSQL("drop table " + mTableName);
						MarketDatabase.getMarketDH().onCreate(marketDB,
								mTableSQL);
					}
					
					// 2.从数据库中查询所需要的数据，如果没有数据就从网络中获取
					int resultCount = getDataFromDB();
					
					if (resultCount == 0) {
						int networkResultCount = getDataFromNetwork(sPreferences);
						if (networkResultCount == 0) {
							mDataResponse.onLoadDataError("已经是最后一页");
							isEnd = true;
							isLoading = false;
							return;
						}
					}
					mDataResponse.onLoadDataComplete(mAppBeanList, totalPage,
							nowPage);
				} else {
					mDataResponse.onLoadDataError("已经是最后一页");
					isEnd = true;
				}
				isLoading = false;
			}
		}.start();
	};

	/**
	 * 从网络获取数据
	 */
	private int getDataFromNetwork(SharedPreferences sPreferences) {
		int count = 0;
		HttpConnection httpCon = new HttpConnection();
		String resultJson = httpCon.requestService(mReqsConfig, new String[] {
				ConstantsTable.KEY_VC, ConstantsTable.NOW_VERSION,
				ConstantsTable.KEY_IMEI, ConstantsTable.IMEI,
				ConstantsTable.KEY_PI, String.valueOf(nowPage),
				ConstantsTable.KEY_PS, ConstantsTable.PAGE_SIZE });
		// String resultJson =
		// "{\"sc\":200,\"rc\":3,\"apps\":[{\"id\":\"h3c001\",\"an\":\"Google I/O\",\"icon\":\"http://img.yingyonghui.com/icon/72/304337.png\",\"pn\":\"com.google.IO\",\"ver\":\"1.1.0\",\"vc\":1,\"sz\":\"2.32Kb\",\"cat\":\"app\",\"dl\":\"http://www.appchina.com/market/e/304337/download.pc/0/E073605F9BD2CF1B29E4874ECF75FAD3/com.google.android.apps.iosched.1340189038990.apk?refererPage=www.download\"},{\"id\":\"h3c002\",\"an\":\"欧洲杯大师\",\"icon\":\"http://img.yingyonghui.com/icon/72/295980.png\",\"pn\":\"com.adidas.EURO\",\"ver\":\"1.1.0\",\"vc\":1,\"sz\":\"6.37Kb\",\"cat\":\"game\",\"dl\":\"http://www.appchina.com/market/e/304337/download.pc/0/E073605F9BD2CF1B29E4874ECF75FAD3/com.google.android.apps.iosched.1340189038990.apk?refererPage=www.download\"}]}";

		// 2.解析信息
		try {
			JSONTokener jsonParser = new JSONTokener(resultJson);
			JSONObject person = (JSONObject) jsonParser.nextValue();
			JSONArray jsonArr = person.getJSONArray("apps");

			int length = jsonArr.length();
			for (int i = 0; i < length; i++) {// 遍历JSONArray
				JSONObject oj = jsonArr.getJSONObject(i);
				AppInfoBean aib = new AppInfoBean();
				aib.APP_ID = oj.getString("id");
				aib.APP_NAME = oj.getString("an");
				aib.APP_ICON = oj.getString("icon");
				aib.APP_PACK = oj.getString("pn");
				aib.APP_VER_NAME = oj.getString("ver");
				aib.APP_VER = oj.getInt("vc");
				aib.APP_SIZE = oj.getString("sz");
				aib.APP_CAT = oj.getString("cat");
				aib.APP_SCORE = oj.getString("score");
				aib.APP_URL = oj.getString("dl");
				mAppBeanList.add(aib);
				count++;
			}
		} catch (JSONException e) {
			mDataResponse.onLoadDataError("数据解析错误");
			Log.d(ConstantsTable.LOG_TAG, "HomepageRec json error!");
			e.printStackTrace();
		}

		// 3.保存至数据库
		new Thread(new Runnable() {
			@Override
			public void run() {
				SQLiteDatabase marketDB = MarketDatabase.getMarketDB();
				// 先清除旧数据
				try{
					marketDB.execSQL("drop table " + mTableName);
					MarketDatabase.getMarketDH().onCreate(marketDB, mTableSQL);
				}catch (Exception e) {
					Log.e(ConstantsTable.LOG_TAG,"DataLoader drop error!!!!========");
				}

				ContentValues tcv = new ContentValues();
				for (AppInfoBean aib : mAppBeanList) {
					tcv.put(HomeRecommendTable.APP_ID, aib.APP_ID);
					tcv.put(HomeRecommendTable.APP_NAME, aib.APP_NAME);
					tcv.put(HomeRecommendTable.APP_ICON, aib.APP_ICON);
					tcv.put(HomeRecommendTable.APP_PACK, aib.APP_PACK);
					tcv.put(HomeRecommendTable.APP_VER_NAME, aib.APP_VER_NAME);
					tcv.put(HomeRecommendTable.APP_VER, aib.APP_VER);
					tcv.put(HomeRecommendTable.APP_SIZE, aib.APP_SIZE);
					tcv.put(HomeRecommendTable.APP_CAT, aib.APP_CAT);
					tcv.put(HomeRecommendTable.APP_SCORE, aib.APP_SCORE);
					tcv.put(HomeRecommendTable.APP_URL, aib.APP_URL);
					marketDB.insert(mTableName, null, tcv);
				}
			}
		}).start();

		// 保存刷新值
		SharedPreferences.Editor editor_isstop = sPreferences.edit();
		editor_isstop.putLong(ConstantsTable.HOMEPAGE_RECOMMEND,
				System.currentTimeMillis());
		editor_isstop.commit();
		return count;
	}

	/**
	 * 从数据库中获取数据
	 */
	private int getDataFromDB() {
		int count = 0;// 返回值个数
		// 获得数据库对象
		SQLiteDatabase marketDB = MarketDatabase.getMarketDB();
		// 查询表中的数据
		Cursor cursor = marketDB.query(
				mTableName,
				null,
				null,
				null,
				null,
				null,
				"_id asc LIMIT "
						+ ((nowPage - 1) * Integer
								.valueOf(ConstantsTable.PAGE_SIZE)) + ","
						+ Integer.valueOf(ConstantsTable.PAGE_SIZE));

		// 获取列的索引
		int id = cursor.getColumnIndex(HomeRecommendTable.ID);
		int appId = cursor.getColumnIndex(HomeRecommendTable.APP_ID);
		int appName = cursor.getColumnIndex(HomeRecommendTable.APP_NAME);
		int appIcon = cursor.getColumnIndex(HomeRecommendTable.APP_ICON);
		int appPack = cursor.getColumnIndex(HomeRecommendTable.APP_PACK);
		int appVerName = cursor.getColumnIndex(HomeRecommendTable.APP_VER_NAME);
		int appVer = cursor.getColumnIndex(HomeRecommendTable.APP_VER);
		int appSize = cursor.getColumnIndex(HomeRecommendTable.APP_SIZE);
		int appCat = cursor.getColumnIndex(HomeRecommendTable.APP_CAT);
		int appScore = cursor.getColumnIndex(HomeRecommendTable.APP_SCORE);
		int appUrl = cursor.getColumnIndex(HomeRecommendTable.APP_URL);

		for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
			AppInfoBean aib = new AppInfoBean();
			aib.ID = cursor.getString(id);
			aib.APP_ID = cursor.getString(appId);
			aib.APP_NAME = cursor.getString(appName);
			aib.APP_ICON = cursor.getString(appIcon);
			aib.APP_PACK = cursor.getString(appPack);
			aib.APP_VER_NAME = cursor.getString(appVerName);
			aib.APP_VER = cursor.getInt(appVer);
			aib.APP_SIZE = cursor.getString(appSize);
			aib.APP_CAT = cursor.getString(appCat);
			aib.APP_SCORE = cursor.getString(appScore);
			aib.APP_URL = cursor.getString(appUrl);
			mAppBeanList.add(aib);
			count++;
		}
		cursor.close();// 关闭结果集
		return count;
	}
}
